package com.cans.lightning.business.system.web;

import com.cans.lightning.base.dto.ResDto;
import com.cans.lightning.business.system.entity.FileInfo;
import com.cans.lightning.business.system.enums.StorageTypeEnum;
import com.cans.lightning.business.system.service.api.IFileInfoService;
import com.cans.lightning.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 文件操作
 *
 * @author shencan
 * @date 2020/6/21 20:16
 */
@RestController
@RequestMapping("/file")
public class FileInfoController {

    private static final Logger logger = LoggerFactory.getLogger(FileInfoController.class);

    @Resource
    private IFileInfoService fileInfoService;


    @PostMapping("/upload")
    public ResDto upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResDto.fait("上传失败，请选择文件");
        }

        try {
            FileInfo upload = fileInfoService.upload(file);
            return ResDto.success(upload);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            return ResDto.fait("上传失败！");
        }


    }

    @GetMapping("/download/{id}")
    public void download(@PathVariable String id, HttpServletResponse response) throws IOException {

        FileInfo fileInfo = fileInfoService.getById(id);

        // 设置相关格式
        response.setContentType("application/force-download");
        // 设置下载后的文件名以及header
        response.addHeader("Content-disposition", "attachment;fileName=" + fileInfo.getFileName() + "." + fileInfo.getFileType());
        // 创建输出对象
        OutputStream os = response.getOutputStream();
        // 常规操作
        byte[] buf = new byte[1024];
        int len;

        switch (StorageTypeEnum.valueOf(fileInfo.getStorageType())) {
            case DEFAULT:
                File file = new File(fileInfo.getFilePath());
                // 文件地址，真实环境是存放在数据库中的
                // 穿件输入对象
                FileInputStream fis = new FileInputStream(file);

                while ((len = fis.read(buf)) != -1) {
                    os.write(buf, 0, len);
                }
                fis.close();

                break;
            case MONGODB:
                break;
        }

    }

    @GetMapping("/img/{id}")
    public void img(@PathVariable String id, HttpServletResponse response) throws IOException {

        FileInfo fileInfo = fileInfoService.getById(id);

        // 文件地址，真实环境是存放在数据库中的
        File file = new File(fileInfo.getFilePath());
        // 穿件输入对象
        FileInputStream fis = new FileInputStream(file);
        // 设置相关格式
        response.setContentType("image/jpeg");
        // 设置下载后的文件名以及header
        response.addHeader("Content-disposition", "inline;fileName=" + fileInfo.getFileName() + "." + fileInfo.getFileType());
        // 创建输出对象
        OutputStream os = response.getOutputStream();
        // 常规操作
        byte[] buf = new byte[1024];
        int len;
        while ((len = fis.read(buf)) != -1) {
            os.write(buf, 0, len);
        }
        fis.close();
    }

    /**
     * 图片预览
     *
     * @param id
     * @param response
     * @return
     */
    @GetMapping("/view-picture/{id}")
    public void viewPicture(@PathVariable String id, HttpServletResponse response) throws IOException {

        if (StringUtils.isEmpty(id) || id.equals("null")) {
            return;
        }

        fileInfoService.view(response.getOutputStream(), id);
    }

}
